<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use EasyWeChat\Factory;
use app\model\JdHistory;
use app\model\JdUser;
use app\model\JdBeanRecord;

class CheckFreeFruit extends Command
{
    protected $app;
    protected function configure()
    {
        // 指令配置
        $this->setName('app\command\checkfreefruit')
            ->setDescription('the app\command\checkfreefruit command');
    }

    protected function execute(Input $input, Output $output)
    {
        $config = config('wechat');
        $this->app = Factory::officialAccount($config);

        $users = JdUser::select();

        foreach ($users as $key => $value) {
            if(!$value->cookie || $value->expired)
                continue;
            $this->getFreeFruit($value, $output);
        }
    }
     protected function taskInitForFarm(JdUser $user, Output $output) {
        $headers = [
            'User-Agent: jdapp;iPhone;9.2.2;14.2;%E4%BA%AC%E4%B8%9C/9.2.2 CFNetwork/1206 Darwin/20.1.0',
        ];
        $response = '';
        try {
            $response = $this->curl_get('https://api.m.jd.com/client.action?functionId=taskInitForFarm&appid=wh5', 
                $user->cookie,
                $headers
            );
            $farmTask = json_decode($response);
            return $farmTask;
        } catch (\Throwable $th) {
            //throw $th;
            $output->writeln("获取用户免费水果出错：{$user->id} {$user->pt_pin} {$th}");
            if($response){
                $output->writeln($response);
            }
        }
        return null;
     }

    protected function getFreeFruit(JdUser $user, Output $output) {
        $farmTask = $this->taskInitForFarm($user, $output);
        $headers = [
            'User-Agent: jdapp;iPhone;9.2.2;14.2;%E4%BA%AC%E4%B8%9C/9.2.2 CFNetwork/1206 Darwin/20.1.0',
            'Accept: application/json,text/plain, */*',
            'Content-Type: application/x-www-form-urlencoded',
            'Accept-Encoding: gzip, deflate, br',
            'Accept-Language: zh-cn',
            'Connection: keep-alive',
            'Referer: https://home.m.jd.com/myJd/newhome.action',
            'origin: https://home.m.jd.com',
            'pragma: no-cache',
            "cache-control: no-cache",
            "sec-fetch-dest: empty",
            "sec-fetch-mode: cors",
            "sec-fetch-site: same-site",
        ];
        $response = '';
        try {
            $response = $this->curl_post('https://api.m.jd.com/client.action?functionId=initForFarm', 
                [
                    "body"=> "{\"version\":4}",
                    "appid" => "wh5",
                    "clientVersion" => "9.1.0"
                ], 
                $user->cookie,
                $headers
            );
            $farmInfo = json_decode($response);
            /*
             // 预测n天后水果课可兑换功能
  let waterTotalT = ($.farmInfo.farmUserPro.treeTotalEnergy - $.farmInfo.farmUserPro.treeEnergy - $.farmInfo.farmUserPro.totalEnergy) / 10;//一共还需浇多少次水

  let waterD = Math.ceil(waterTotalT / waterEveryDayT);

  message += `【预测】${waterD === 1 ? '明天' : waterD === 2 ? '后天' : waterD + '天之后'}(${timeFormat(24 * 60 * 60 * 1000 * waterD + Date.now())}日)可兑换水果🍉`
            
            */
            $output->writeln("免费水果状态：({$user->pt_pin} {$user->mobile}): {$farmInfo->treeState}");
            if($farmInfo->treeState === 2 || $farmInfo->treeState === 3){
                if(!$user->got_free_fruit) {
                    $user->got_free_fruit=1;
                    $user->save();
                    $this->notifyGotFruit($user);
                }
                $user->tip ="已经获得免费水果";
                $output->writeln("已经获得免费水果：{$user->pt_pin} {$user->mobile} {$user->remark}");
            } else {
                if($farmInfo->farmUserPro){
                    $waterTotalT = ($farmInfo->farmUserPro->treeTotalEnergy - $farmInfo->farmUserPro->treeEnergy - $farmInfo->farmUserPro->totalEnergy) / 10;
                    if($farmTask && $farmTask->totalWaterTaskInit->totalWaterTaskTimes) {
                        $waterEveryDayT = $farmTask->totalWaterTaskInit->totalWaterTaskTimes;
                        $waterD = ceil($waterTotalT / $waterEveryDayT);
                        if($waterD == 1) {
                            $user->tip = "预测明天可兑换水果";
                        } else if($waterD == 2){
                            $user->tip = "预测后天可兑换水果";
                        } else {
                            $user->tip = "预测".$waterD."天之后可兑换水果";
                        }
                        
                    } else {
                        $current = $farmInfo->farmUserPro->treeEnergy + $farmInfo->farmUserPro->totalEnergy;
                        $total = $farmInfo->farmUserPro->treeTotalEnergy;
                        $user->tip = "水果进度{$current}/{$total},一共还需浇 $waterTotalT 次水";
                    }
                  $output->writeln($user->tip);
                    $user->save();
                }
                if($user->got_free_fruit) {
                    $user->got_free_fruit=0;
                    $user->save();
                }
            }
            
        } catch (\Throwable $th) {
            //throw $th;
            $output->writeln("获取用户免费水果出错：{$user->id} {$user->pt_pin} {$th}");
            if($response){
                $output->writeln($response);
            }
            
        }
       
    }
    
    public function notifyGotFruit(JdUser $user){
        try {
            $config = config('wechat');
            $sendResult = $this->app->template_message->send([
                'touser' => $user->openid,
                'template_id' => $config['template_ids']['got_fruit'],
                'url' => "https://t.0xaa.cn/index/data?id={$user->id}",
                 'data' => [
                    'Account' => "{$user->pt_pin} ({$user->nickname} {$user->mobile} {$user->remark})"
                ]
            ]);
            echo json_encode($sendResult);
            return $sendResult;
        } catch (\Throwable $th) {
            throw $th;
            return false;
        }
    }

    function curl_post($url , $data=array(), $cookie,  $headers, $enableGzip = true){

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        //至关重要，CURLINFO_HEADER_OUT选项可以拿到请求头信息
        curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
       
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15); //timeout in seconds
        if($enableGzip) {
            curl_setopt($ch,CURLOPT_ENCODING , "gzip");
        }
        
        $output = curl_exec($ch);
        //通过curl_getinfo()可以得到请求头的信息
        // $responseHeader=curl_getinfo($ch);
        // echo json_encode($responseHeader);
        curl_close($ch);
        return $output;

    }
    
    function curl_get($url , $cookie,  $headers, $enableGzip = true){

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        //至关重要，CURLINFO_HEADER_OUT选项可以拿到请求头信息
        curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
       
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15); //timeout in seconds
        if($enableGzip) {
            curl_setopt($ch,CURLOPT_ENCODING , "gzip");
        }
        
        $output = curl_exec($ch);
        //通过curl_getinfo()可以得到请求头的信息
        // $responseHeader=curl_getinfo($ch);
        // echo json_encode($responseHeader);
        curl_close($ch);
        return $output;

    }
}
